package com.niit.class_3.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //判断是否是不用登录的页面 。
        //如何获取请求页面的地址 。
        //把父类的引用，强制转换为子类的对象，才能够调用子类的方法
        HttpServletRequest req = (HttpServletRequest)request ;
        String path = req.getRequestURI();
        if(checkPath(path)){
            //true
            chain.doFilter(request, response);
        }else{
            //判断用户是否登录  判断session会话对象中是否有值
            HttpSession session = req.getSession() ;
            Object obj = session.getAttribute("user");
            if(obj == null){
                //跳转到登录界面
                HttpServletResponse res = (HttpServletResponse)response;
                res.sendRedirect("login.html");
            }else{
                //请求继续向后流转
                chain.doFilter(request, response);
            }
        }
    }

    public boolean checkPath(String path){
        boolean flag = false;
        //这些页面不需要经过登录过滤器
        String[] ps = {"login.html", "LoginServlet",".js" , ".css"};
        //判断请求路径中，有没有包含上面路径中的某一项
        for (int i = 0; i < ps.length; i++) {
            if(path.endsWith(ps[i])){
                //表示是指定地址中的某一个 。
                flag = true;
                break ;
            }
        }
        return flag;
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
